import type { App } from 'vue'

export function nextInput (app: App<Element>) {
  app.directive('nextInput', {
    mounted (el, binding) {
      el.addEventListener('keypress', (e) => {
        e = e || window.event
        const charcode = typeof e.charCode == 'number' ? e.charCode : e.keyCode
        if (charcode == 13) {
          e.preventDefault()
          const dom = document.getElementsByName(binding.value)
          for (let i = 0; i < dom.length; i++) {
            if (dom[i] == document.activeElement) {
              if (i == dom.length) return
              if (!dom[i + 1]) return
              if ((dom[i + 1] as any).name === binding.value) {
                focusNextInput(dom, i + 1)
                return
              }
            }
          }
        }
      })
    }
  })
}

function focusNextInput (inputs, index: number) {
  if (index < inputs.length) {
    if (inputs[index].disabled) {
      focusNextInput(inputs, index + 1)
    } else {
      inputs[index].focus()
    }
  }
}
